package com.dxy.dao.impl;



import com.dxy.dao.BaseAdminDao;
import com.dxy.utils.DruidUtil;

import java.sql.*;

/**
 * @author DELL
 */
public class BaseAdminDaoImpl implements BaseAdminDao {

    private static final String SQL_UPDATE_LOGIN_TIME ="UPDATE admin SET LOGINTIME=?,LOGINIP=? WHERE USERNAME=?";
    private static final String SQL_LOGIN ="SELECT ID FROM admin WHERE USERNAME=? AND PASSWORD=?";



    /**
     * g根据用户名，更新登录时间和登录IP
     *
     * @param username
     * @param date
     * @param ip
     */
    @Override
    public void updateLoginTime(String username, java.util.Date date, String ip) {
        //1.获取数据库连接
        Connection connection = DruidUtil.getConnection();
        PreparedStatement preparedStatement=null;

        try {
            //2.预编译sql语句
            preparedStatement = connection.prepareStatement(SQL_UPDATE_LOGIN_TIME);
            //3.填充参数
            preparedStatement.setDate(1,new Date(date.getTime()));
            preparedStatement.setString(2,ip);
            preparedStatement.setString(3,username);
            //4.执行sql
            preparedStatement.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //5.释放资源
            DruidUtil.close(connection,preparedStatement,null);
        }

    }

    /**
     * 管理员根据账号登录登录
     *
     * @param username
     * @param password
     * @return 登录结果 true成功 false 失败
     */
    @Override
    public boolean login(String username, String password) {
        //1.获取数据库连接
        Connection connection = DruidUtil.getConnection();
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;

        try {
            //2.预编译sql语句
            preparedStatement = connection.prepareStatement(SQL_LOGIN);
            //3.填充参数
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            //4.执行sql
             resultSet = preparedStatement.executeQuery();
             //根据查询结果返回 True
             return resultSet.next();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //5.释放资源
            DruidUtil.close(connection,preparedStatement,resultSet);
        }
        return false;
    }
}
